import { SelectProps, Space } from "antd"
import { FormInstance } from "antd/lib"
import { FC, useEffect, useState } from "react"

import { SFormItem } from "@/components/common"
import StyleSelect from "@/components/common/styleSelect"
import { useApi } from "@/hooks"
import { useLocale } from "@/locales"

type OrderTypeOptions = {
	type: number
	parentType: number
	desc: string
	sortValue: number
	enable: boolean
	subList: OrderTypeOptions[]
}

const OrderType: FC<any> = ({ form }: { form: FormInstance<any> }) => {
	const { newFormat } = useLocale()
	const [parentOrderType, setParentOrderType] = useState(0)
	const [options, setOptions] = useState<OrderTypeOptions[]>([])
	const [orderTypeoptions, setOrderTypeOptions] = useState<SelectProps["options"]>([])
	const { generalHttpB } = useApi()

	useEffect(() => {
		;(async () => {
			const [err, data] = await generalHttpB<OrderTypeOptions[]>("/dx-game-data-manager/order/getOrderTypeSection", undefined)
			if (err) {
				setOptions([])
				return
			}
			setOptions(data)
		})()
	}, [])

	useEffect(() => {
		form.setFieldValue("orderType", undefined)
		const orderType = options.find(item => item.type === parentOrderType)
		if (!orderType) {
			setOrderTypeOptions([])
			return
		}
		setOrderTypeOptions(orderType.subList.map(item => ({ label: item.desc, value: item.type })))
	}, [parentOrderType])

	return (
		<Space size={[16, 16]} wrap>
			<Space.Compact>
				<SFormItem name="parentOrderType" label={newFormat("label.orderType")}>
					<StyleSelect
						placeholder={newFormat("common.select_all")}
						allowClear
						options={options.map(item => ({ label: item.desc, value: item.type }))}
						onChange={v => setParentOrderType(v as number)}
					/>
				</SFormItem>
			</Space.Compact>
			<Space.Compact>
				<SFormItem name="orderType" label={newFormat("label.orderSubclass")}>
					<StyleSelect placeholder={newFormat("common.select_all")} allowClear options={orderTypeoptions} />
				</SFormItem>
			</Space.Compact>
		</Space>
	)
}

export default OrderType
